package thread;

/**
 * 死锁
 * 死锁的产生:
 * 两个线程个字吃有一个锁对象的同时等待对方先释放对象,此时会出现僵持状态
 * 这个现象就是死锁
 *
 * @author Luka
 * @date 2021/06/04 17:10
 **/
public class DeadLockDemo {
    //定义两个锁对象，"筷子"和"勺"
    public static Object chopsticks = new Object();
    public static Object spoon = new Object();

    public static void main(String[] args) {
        Thread np = new Thread(){
            public void run(){
                System.out.println("北方人开始吃饭.");
                System.out.println("北方人去拿筷子...");
                synchronized (chopsticks){
                    System.out.println("北方人拿起了筷子开始吃饭...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                    System.out.println("北方人吃完了饭，去拿勺...");
                    synchronized (spoon){
                        System.out.println("北方人拿起了勺子开始喝汤...");
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                        }
                        System.out.println("北方人喝完了汤");
                    }
                    System.out.println("北方人放下了勺");
                }
                System.out.println("北方人放下了筷子，吃饭完毕!");
            }
        };


        Thread sp = new Thread(){
            public void run(){
                System.out.println("南方人开始吃饭.");
                System.out.println("南方人去拿勺...");
                synchronized (spoon){
                    System.out.println("南方人拿起了勺开始喝汤...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                    System.out.println("南方人喝完了汤，去拿筷子...");
                    synchronized (chopsticks){
                        System.out.println("南方人拿起了筷子开始吃饭...");
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                        }
                        System.out.println("南方人吃完了饭");
                    }
                    System.out.println("南方人放下了筷子");
                }
                System.out.println("南方人放下了勺，吃饭完毕!");
            }
        };

        np.start();
        sp.start();



    }
}